<?php

namespace App\Logic;

use App\common;
use App\Dos\RegisterDos;
use App\server\JwtServer;
use http\Exception\RuntimeException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use App\Models\BackUsers;

class RegisterLogic
{
    /**
     * 启动Session
     * RegisterLogic constructor.
     */
    public function __construct()
    {
        Session::start();
    }

    /**
     *  '注册数据入库
     * @param $data
     */
    public static function RegisterFunction($vaLiDate)
    {
        $vaLiDate['password'] = common::lock_url($vaLiDate['password']); // 密码加密
        $userSql = BackUsers::userFirst('username', $vaLiDate['username']); //查询用户是否存在
        if (empty($userSql))
            return $loginSql = BackUsers::userAdd($vaLiDate);
    }

    /**
     *  '进行登录
     * @param $message
     */
    public static function loginMessage($vaLiDate)
    {
        $vaLiDate['password'] = common::lock_url($vaLiDate['password']); // 密码加密
        if (empty($vaLiDate)) throw new \RuntimeException('参数不能为空');
        $sqlFirst = BackUsers::userFirst('username', $vaLiDate['username']);  //查询用户是否存在
        if (!empty($sqlFirst) && Hash::check($vaLiDate['password'], $sqlFirst->password)) {
            $token = JwtServer::jwtEncode($sqlFirst);
            return $token;
        } else {
            $sqlData = BackUsers::login($vaLiDate);
            $token = JwtServer::jwtEncode($sqlData);
            return $token;
        }
    }


    /**
     * @function  授权登录
     */
    public function indexFunction($code, $nickName, $avatarUrl)
    {
        $configApi = config('api');
        $url = $configApi['api']['url'];
        $configApi['api']['js_code'] = $code;
        unset($configApi['api']['url']);
        $param = http_build_query($configApi['api']);
        $data = $url . '?' . $param;
        $data = json_decode(file_get_contents($data), true);
        if ($data == 'errorCode') throw new \Exception('false');
        throw new \Exception(true);
    }
}
